package com.iflytek.edu.db.core.strategy;

import cn.hutool.core.lang.Assert;
import com.alibaba.druid.DbType;
import com.iflytek.edu.db.core.exception.DbTypeNotSupportedException;
import com.iflytek.edu.db.core.parse.SqlAdapterConfig;
import com.iflytek.edu.db.core.strategy.dm.function.DmNewIdFuncStrategy;
import com.iflytek.edu.db.core.strategy.dm.function.DmScopeIdentityFuncStrategy;
import com.iflytek.edu.db.core.strategy.dm.function.DmWmConcatFuncStrategy;
import com.iflytek.edu.db.core.strategy.dm.grammar.DmBacktickGrammarStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略工厂
 *
 * @author linkai
 * @date 2022/2/11
 */
public class StrategyFactory {
    private final static Map<DbType, SqlAdapterConfig> strategyMap = new ConcurrentHashMap<>();

    public static SqlAdapterConfig createConfig(DbType type) {
        Assert.notNull(type, "数据库类型不能为空");
        SqlAdapterConfig config = strategyMap.get(type);
        if (Objects.nonNull(config)) {
            return config;
        }
        switch (Objects.requireNonNull(type)) {
            case dm:
                config = dmConfig(type);
                break;
            default:
                throw new DbTypeNotSupportedException("不支持该类型： " + type);
        }
        strategyMap.put(type, config);
        return config;
    }

    private static SqlAdapterConfig dmConfig(DbType type) {
        SqlAdapterConfig config = new SqlAdapterConfig();
        config.setDbType(type);

        List<GrammarStrategy> grammarList = new ArrayList<>();
        grammarList.add(new DmBacktickGrammarStrategy());

        List<FunctionStrategy> funcList = new ArrayList<>();
        funcList.add(new DmWmConcatFuncStrategy());
        funcList.add(new DmScopeIdentityFuncStrategy());
        funcList.add(new DmNewIdFuncStrategy());

        config.setGrammarStrategyList(grammarList);
        config.setFuncStrategyList(funcList);
        return config;
    }
}
